# -*- coding: utf-8 -*-


import json
import sys
import platform
import os

## setting env variable
EN_PATH = os.path.dirname(os.path.abspath(__file__));
os.environ["EN_PATH"] = EN_PATH

from command import base, component_manager, common



# ## 检查en工具是否已经安装
# def isEnInstalled():
#     ret = base.is_file("en.data")
#     if ret == 0:
#         return True;
#     else:
#         return False;

## 是否是windows操作系统
def is_windows():
  host_platform = platform.system().lower()
  if (host_platform == "darwin"):
    host_platform = "mac"
  if "windows" == host_platform:
    return True
  return False




# ## windows环境下安装
# def installForWindows():
#     return;

# ## linux环境下安装
# def installForLinux():
#     return;


# ## 安装en命令行工具
# def install():
#     if isEnInstalled():
#         return
    
#     if is_windows():
#         installForWindows()
#     else:
#         installForLinux()
    


## 打印帮助
def printHelp(command = None):
    if command == 'install':
        print("用法：en install [组件] <参数>")
        print("[组件]：")
        coms = component_manager.ALL_COMPONENTS.keys();
        list = []
        for c in coms:
            list.append((c + "(已安装)" ) if component_manager.is_install(c) else c)
        print("\n".join(list))
        print("\n\n")
        print("[参数]：")
        print("-r\t\t指定安装的版本")
        print("-l\t\t输出更多日志")
        return;
    if command == 'update':
        print("用法：en update [组件] <参数>")
        print("[组件]：")
        coms = component_manager.ALL_COMPONENTS.keys();
        list = []
        for c in coms:
            list.append((c + "(已安装)" ) if component_manager.is_install(c) else c)
        print("\n".join(list))
        print("\n\n")
        print("[参数]：")
        print("-r\t\t指定安装的版本")
        print("-l\t\t输出更多日志")
        return;
    if command == 'uninstall':
        print("用法：en uninstall [组件] <参数>")
        print("[组件]：")
        coms = component_manager.ALL_COMPONENTS.keys();
        list = []
        for c in coms:
            if component_manager.is_install(c):
                list.append(c + "(已安装)" );
        print("\n".join(list))
        print("\n\n")
        print("[参数]：")
        print("-l\t\t输出更多日志")
        print("-d\t\t连同所有依赖一起卸载")
        return;

    print("用法：en [命令] ")
    print("[命令]：")
    print("install\t\t安装组件")
    print("update\t\t更新组件")
    print("check\t\t检查组件是否已安装")
    print("status\t\t检查组件是否正在运行")
    print("uninstall\t\t卸载组件")
    print("test\t\t测试组件")
    print("ip\t\t修改IP")

    print("list\t\t列出所有可安装组件")
    print("upgrade\t\t更新en工具")
    print("")
    print("[参数]：")
    print("-l\t\t输出更多日志")


## 打印版本
def printVersion():
    print("1.0")
    return;


## 打印错误
def printError(content : str):
    print(f"{content}，更多详细用法，请输入 en -h 查看")
    return;


def en(args: list):

    commands = ["install", "update", "check", "status", "uninstall", "upgrade", "test", "list"]
    commands.extend(['anzhuang', 'xiezai', 'jiancha', 'zhuangtai', 'shengji', 'ceshi', 'liebiao'])
    commands.extend(['ip'])
    commands.extend(['init'])

    # 输出更多日志
    if args.__contains__("-l") or args.__contains__("--log"):
        common.LOG = True


    if args.__contains__("-h") or args.__contains__("--help"):
        if len(args) <= 1:
            printHelp();
            return 0;
        else:
            command = args[0]
            if command not in commands:
                printError(f"{command} 不属于命令，[命令]只包含 {'/'.join(commands)}");
                return 1
            printHelp(command)
            return 0
    if args.__contains__("-v") or args.__contains__("--version"):
        printVersion();
        return 0
    if args.__contains__("-v") or args.__contains__("--version"):
        printVersion();
        return 0
    

    ## 判断命令长度
    if args.__len__() < 1:
        printError("命令调用格式必须是 en [命令] [选项]");
        return 1
    command = args[0]

    rVersion = None
    for i in range(len(args)):
        item = args[i]
        if item == '-r':
            i += 1
            rVersion = args[i]

    if command not in commands:
        printError(f"{command} 不属于命令，[命令]只包含 {'/'.join(commands)}");
        return 1
    
    if command == 'list' or command == 'liebiao':
        # 列出可安装组件
        coms = component_manager.ALL_COMPONENTS.keys();
        list = []
        for c in coms:
            list.append((c + "(已安装)" ) if component_manager.is_install(c) else c)
        
        print("可以安装的组件如下:")
        print("\n".join(list))
        return 0;
    
    if command == 'upgrade' or command == 'shengji':
        # 执行git pull 更新 en 工具
        EN_PATH = base.get_env("EN_PATH");
        if is_windows():
            base.cmd_in_dir(EN_PATH, "./update.bat")
        else:
            base.cmd_in_dir(EN_PATH, "./update.sh")
        return;

    ## 修改IP
    # if command == 'ip':
    #     ret = base.cmd("nmtui", ["-h"], True)
    #     if ret != 0:
    #         if base.is_apt():
    #             base.cmd("apt", ["install", "network-manager", "-y"], True)
    #         else:
    #             base.cmd("yum", ["install", "network-manager", "-y"], True)
    #     base.cmd("nmtui", [])
    #     return 0;

    ## 修改IP
    if command == 'init':

        if base.is_apt():

            # 安装docker环境
            if not base.is_kylin():
                base.cmd("apt", ["update"], True)
                base.cmd("apt", ["install", "-y", "apt-transport-https", "ca-certificates", "curl", "software-properties-common"], True)
                
                ## 这句在安装过程中会运行失败，不太确定会不会影响docker安装
                # base.cmd("curl", ["-fsSL", "https://download.docker.com/linux/ubuntu/gpg", "|", "sudo", "apt-key", "add", "-"], True);
                base.cmd("apt", ["add-apt-repository", '"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"'], True);
                base.cmd("apt", ["update"], True);


            # base.cmd("apt", ["install", "network-manager", "-y"], True)
        # else:
            # base.cmd("yum", ["install", "network-manager", "-y"], True)

        # if os.path.isdir("/etc/netplan"):
        #     files = os.listdir("/etc/netplan")

        #     # TODO 此处需要判断yaml是否已安装
        #     import yaml
        #     for f in files:
        #         netplan_str = ''
        #         with open(f'/etc/netplan/{f}', mode='r') as ff:
        #             netplan_obj = dict()
        #             netplan_obj['network'] = dict()
        #             network_obj : dict = netplan_obj['network']
        #             network_obj['version'] = 2
        #             # if network_obj.get('renderer') == None:
        #             network_obj['renderer'] = 'NetworkManager'
        #             netplan_str = yaml.safe_dump(netplan_obj)
        #         base.writeFile(f"/etc/netplan/{f}", netplan_str)
        #         base.cmd("netplan", ['apply'], True)
        #         base.cmd("systemctl", ['disable', '--now', 
        #                             'systemd-networkd.service', 
        #                             'systemd-networkd.socket', 
        #                             'networkd-dispatcher.service'], True)
        #         base.cmd("systemctl", ['restart', 'NetworkManager'], True)
            
        #     # 把netplan去除
        #     # base.cmd("systemctl", ['disable', '--now', 
        #     #                         'systemd-networkd.service', 
        #     #                         'systemd-networkd.socket', 
        #     #                         'networkd-dispatcher.service'], True)
        #     # base.cmd("systemctl", ['restart', 'NetworkManager'], True)
        #     # base.cmd("apt", ['purge', 'netplan', 'netplan.io', '-y'], True)
        # return 0;
    
    ## 判断命令长度
    if args.__len__() < 2:
        printError("命令调用格式必须是 en [命令] [选项]");
        # printHelp();
        return 1
    
    component = args[1]
    
    com = component_manager.ALL_COMPONENTS.get(component)
    if com is None:
        printError(f"该工具并不支持组件 {component} 的操作，请使用 en list 查询可安装的组件");
        return;


    ## 安装
    if command == 'install' or command == 'anzhuang':
        if common.LOG:
            print(f"准备安装的版本是 {rVersion}")

        ## 检查是否已安装
        if component_manager.is_install(component):
            print(f"该组件已安装")
            return 0
        
        if not base.ping("registry.cn-shenzhen.aliyuncs.com"):
            print(f"当前没有网络，无法安装")
            return 0;
        component_manager.run_install(component, rVersion)
        print(f"{component} 安装成功")
        return 0;


    ## 更新
    if command == 'update' or command == 'gengxin':
        
        if not base.ping("registry.cn-shenzhen.aliyuncs.com"):
            print(f"当前没有网络，无法更新")
            return 0;
        ## 检查是否已安装
        if component_manager.is_install(component):
        
            if not base.ping("registry.cn-shenzhen.aliyuncs.com"):
                print(f"当前没有网络，无法更新")
                return 0;

            component_manager.run_update(component, rVersion)
            print(f"{component} 更新完毕")
            return 0
        printError(f"该组件未安装，请先执行 en install {component} 安装")
        return 0


    ## 卸载
    if command == 'uninstall' or command == 'xiezai':
        
        if not base.ping("registry.cn-shenzhen.aliyuncs.com"):
            print(f"当前没有网络，无法卸载")
            return 0;
        ## 检查是否已安装
        if not component_manager.is_install(component):
            print(f"该组件已卸载")
            return 0
        
        if not base.ping("registry.cn-shenzhen.aliyuncs.com"):
            print(f"当前没有网络，卸载之后将无法重装，请确保网络正常再执行卸载。")
            return 0;
        
        component_manager.run_uninstall(component)
        print(f"{component} 卸载成功")
        return 0;

    ## 检查是否已安装
    if command == 'check' or command == 'jiancha':
        ## 检查是否已安装
        comp = component_manager.ALL_COMPONENTS[component]
        if comp.check():
            print(f"{component} 已安装")
        else:
            print(f"{component} 未安装")
        return 0;


    ## 检查是否已运行
    if command == 'status'  or command == 'zhuangtai':
        ## 检查是否已安装
        comp = component_manager.ALL_COMPONENTS[component]
        if comp.status():
            print(f"{component} 运行中")
        else:
            print(f"{component} 未运行")
        return 0;


## en 命令行方法
def main(args: list):
    try:
        return en(args)
    except Exception as e:
        print(e)
        return 1




if __name__ == '__main__':

    sys.exit(main(sys.argv[1:]))